package com.lyq.pdf.pdfbox;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.TextPosition;
import org.springframework.util.CollectionUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * This is an example on how to get the x/y coordinates and size of each character in PDF
 * 获取PDF中每个字符的x/y坐标和大小
 */
public class GetCharLocationAndSize extends PDFTextStripper {

    static List<List<TextPosition>> lines;

    public GetCharLocationAndSize() throws IOException {
    }

    public void generatePicture() throws IOException {
        PDDocument document = null;

        long singleStart = System.currentTimeMillis();
        try {
            // 获取在线 PDF 的 URL
//            URL url = new URL("https://q-independent.aixuexi.com/B:1006:K/1678982400/3064faf90ad34a29a4b3da73b84282de.pdf");
            URL url = new URL("https://q-independent.aixuexi.com/B:1006:K/1681142400/5f70b0f5b7f14299a21043cbcfd3b7a2.pdf");

            document = PDDocument.load(url.openStream());

            PDFRenderer pdfRenderer = new PDFRenderer(document);

            for (int j = 1; j <= document.getNumberOfPages(); j++) {
                // 获取当前页的图片
//                BufferedImage image = pdfRenderer.renderImageWithDPI(j - 1, 300);
                BufferedImage image = pdfRenderer.renderImage(j - 1, 2);
                // 保存图片
                ImageIO.write(image, "PNG", new File("output-" + j + ".png"));
            }
        } finally {
            if (document != null) {
                document.close();
            }
        }
        long singleStartEnd = System.currentTimeMillis();
        System.out.println("单次耗时：" + (singleStartEnd - singleStart));
    }

    public void parseText() throws IOException {
        long start = System.currentTimeMillis();
        PDDocument document = null;
        /*List<String> fileNameList = new ArrayList<String>(){{
            add("D://手动模式暂停继续两个学习中复现(副本) - 副本.pdf");
            add("D://手动模式暂停继续两个学习中复现(副本) - 副本 (2).pdf");
            add("D://手动模式暂停继续两个学习中复现(副本) - 副本 (3).pdf");
            add("D://手动模式暂停继续两个学习中复现(副本) - 副本 (4).pdf");
            add("D://手动模式暂停继续两个学习中复现(副本) - 副本 (5).pdf");
            add("D://手动模式暂停继续两个学习中复现(副本) - 副本 (6).pdf");
            add("D://手动模式暂停继续两个学习中复现(副本) - 副本 (7).pdf");
            add("D://手动模式暂停继续两个学习中复现(副本) - 副本 (8).pdf");
            add("D://手动模式暂停继续两个学习中复现(副本) - 副本 (9).pdf");
            add("D://手动模式暂停继续两个学习中复现(副本) - 副本 (10).pdf");
        }};*/

//        String fileName = "D:\\手动模式暂停继续两个学习中复现(副本).pdf";
//        String fileName = "D:\\只有解答题(副本).pdf";
//        String fileName = "D:/wy创建计划1.pdf";
//        String fileName = "D:/定制练1.pdf";

        for (int i = 0; i < 1; i++) {
            long singleStart = System.currentTimeMillis();
            try {
                // 获取在线 PDF 的 URL
//                URL url = new URL("https://q-independent.aixuexi.com/B:1006:K/1678982400/3064faf90ad34a29a4b3da73b84282de.pdf");
//                URL url = new URL("https://q-independent.aixuexi.com/B:1006:K/1678982400/7c60c25918ae4d99b3e9500295992b40.pdf");
//                URL url = new URL("https://q-independent.aixuexi.com/B:1006:K/1680105600/ff9389315b714cef96f2cd149ce6ba40.pdf");
                URL url = new URL("https://q-independent.aixuexi.com/B:1006:K/1681142400/5f70b0f5b7f14299a21043cbcfd3b7a2.pdf");

                document = PDDocument.load(url.openStream());
//                document = PDDocument.load(new File(fileNameList.get(i)));
//                document = PDDocument.load(new File(fileName));

                PDFTextStripper stripper = new GetCharLocationAndSize();
                Writer dummy = new OutputStreamWriter(new ByteArrayOutputStream());

                PDFRenderer pdfRenderer = new PDFRenderer(document);

                for (int j = 1; j <= document.getNumberOfPages(); j++) {
//                for (int j = 1; j <= 2; j++) {
                    // 获取当前页的图片
//                    BufferedImage image = pdfRenderer.renderImageWithDPI(j - 1, 300);
//                    BufferedImage image = pdfRenderer.renderImage(j - 1, 2);
                    // 保存图片
//                    ImageIO.write(image, "PNG", new File("output-" + j + ".png"));

                    lines = new ArrayList<>();

                    PDRectangle pdRectangle = document.getPage(j - 1).getMediaBox();
                    float width = pdRectangle.getWidth();
                    float height = pdRectangle.getHeight();
                    System.out.println("第几页：" + j + " width：" + width + " height：" + height);
//                    System.out.println("第几页：" + j + " lower left x：" + pdRectangle.getLowerLeftX() + " lower left y：" + pdRectangle.getLowerLeftY());
//                    System.out.println("第几页：" + j + " upper right x：" + pdRectangle.getUpperRightX() + " upper right y：" + pdRectangle.getUpperRightY());

//                    float cropBoxLowerLeftX = document.getPage(j - 1).getCropBox().getLowerLeftX();
//                    float cropBoxLowerLeftY = document.getPage(j - 1).getCropBox().getLowerLeftY();
//                    float cropBoxUpperRightX = document.getPage(j - 1).getCropBox().getUpperRightX();
//                    float cropBoxUpperRightY = document.getPage(j - 1).getCropBox().getUpperRightY();
//
//                    float trimBoxLowerLeftX = document.getPage(j - 1).getTrimBox().getLowerLeftX();
//                    float trimBoxLowerLeftY = document.getPage(j - 1).getTrimBox().getLowerLeftY();
//                    float trimBoxUpperRightX = document.getPage(j - 1).getTrimBox().getUpperRightX();
//                    float trimBoxUpperRightY = document.getPage(j - 1).getTrimBox().getUpperRightY();
//
//                    float bleedBoxLowerLeftX = document.getPage(j - 1).getBleedBox().getLowerLeftX();
//                    float bleedBoxLowerLeftY = document.getPage(j - 1).getBleedBox().getLowerLeftY();
//                    float bleedBoxUpperRightX = document.getPage(j - 1).getBleedBox().getUpperRightX();
//                    float bleedBoxUpperRightY = document.getPage(j - 1).getBleedBox().getUpperRightY();
//
//                    System.out.println("第几页：" + j + " CropBox: (" + cropBoxLowerLeftX + ", " + cropBoxLowerLeftY + ") - (" + cropBoxUpperRightX + ", " + cropBoxUpperRightY + ")");
//                    System.out.println("第几页：" + j + " TrimBox: (" + trimBoxLowerLeftX + ", " + trimBoxLowerLeftY + ") - (" + trimBoxUpperRightX + ", " + trimBoxUpperRightY + ")");
//                    System.out.println("第几页：" + j + " BleedBox: (" + bleedBoxLowerLeftX + ", " + bleedBoxLowerLeftY + ") - (" + bleedBoxUpperRightX + ", " + bleedBoxUpperRightY + ")");

                    stripper.setSortByPosition(true);
                    stripper.setStartPage(j);
//                    stripper.setEndPage(document.getNumberOfPages());
                    stripper.setEndPage(j);

                    stripper.writeText(document, dummy);

//                    for (List<TextPosition> positionList : lines) {
//                        List<TextPosition> textPositions = positionList.stream().filter(textPosition -> "#".equals(textPosition.getUnicode())).collect(Collectors.toList());
//                        if (!CollectionUtils.isEmpty(textPositions)) {
//                            TextPosition textPosition = textPositions.get(0);
//                            System.out.println(textPosition.getUnicode() + " [(X=" + textPosition.getXDirAdj() + ",Y=" +
//                                    textPosition.getYDirAdj() + ") height=" + textPosition.getHeightDir() + " width=" +
//                                    textPosition.getWidthDirAdj() + "]");
//                        }
//                    }
                }
            } finally {
                if (document != null) {
                    document.close();
                }
            }
            long singleStartEnd = System.currentTimeMillis();
            System.out.println("单次耗时：" + (singleStartEnd - singleStart));
        }

        long end = System.currentTimeMillis();
        System.out.println("总耗时：" + (end - start));
    }

    /**
     * @throws IOException If there is an error parsing the document.
     */
    public static void main(String[] args) throws IOException {
        GetCharLocationAndSize getCharLocationAndSize = new GetCharLocationAndSize();
        getCharLocationAndSize.parseText();
//        getCharLocationAndSize.generatePicture();
    }

    /**
     * Override the default functionality of PDFTextStripper.writeString()
     */
    @Override
    protected void writeString(String string, List<TextPosition> textPositions) throws IOException {
        lines.add(textPositions);
        System.out.println(string);
//        for (TextPosition text : textPositions) {
//            System.out.println(text.getUnicode() + " [(X=" + text.getXDirAdj() + ",Y=" +
//                    text.getYDirAdj() + ") height=" + text.getHeightDir() + " width=" +
//                    text.getWidthDirAdj() + "]");
//        }
    }
}
